package com.zfx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zfx.client.ITemplateClient;
import com.zfx.mapper.ISecondarySystemFunctionMessageMapper;
import com.zfx.mapper.ISecondarySystemPeopleMessageMapper;
import com.zfx.pojo.*;
import com.zfx.service.*;
import com.zfx.util.DataUtil;
import com.zfx.util.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: zfx
 * @version: 1.0
 * @time: 2020-05-10 19:36
 * <p>
 * 修改历史：
 * 修改日期      修改人员    版本    内容
 * 2020-05-10   zfx       1.0
 */
@RestController
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private ILevel1SystemService level1SystemService;

    @Autowired
    private IWorkPlanService workPlanService;

    @Autowired
    private ISecondarySystemFunctionMessageService secondarySystemFunctionMessageService;

    @Autowired
    private ISecondarySystemPeopleMessageService secondarySystemPeopleMessageService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITemplateClient templateClient;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IContractRemindService contractRemindService;

    private static final int SECONDARY_SYSTEM_NUM = 8;
    private static final int FOUNDATION_PLATFORM_SYSTEM_NUM = 1;
    private static final int INTERFACE_SYSTEM_NUM = 2;
    private static final int SERVICE_SYSTEM_NUM = 3;
    private static final int APPLICATION_APPLET_SYSTEM_NUM = 41;
    private static final int APPLICATION_H5_SYSTEM_NUM = 42;
    private static final int APPLICATION_CLIENT_SYSTEM_NUM = 43;
    private static final int APPLICATION_PC_SYSTEM_NUM = 44;
    private static final int APPLICATION_TENCENT_SYSTEM_NUM = 45;


    @RequestMapping("/list")
    public JsonObject getList(HttpServletRequest request, @RequestBody String jsonData) throws IOException {
        JsonObject jsonObject = new JsonObject();
        ObjectMapper objectMapper = new ObjectMapper();

        HashMap<String, Object> dataMap = objectMapper.readValue(jsonData, HashMap.class);

        Level1System level1System = new Level1System(dataMap);
        String userId = String.valueOf(request.getSession().getAttribute("userId"));
        String stateNum = level1System.getState();
        level1System.setState("%"+userId+"%");

        Map<String, Object> map = level1SystemService.findByLevel1System(level1System, userId, stateNum,
                (int) dataMap.get("page"), (int) dataMap.get("limit"));

        jsonObject.setDataSize((int) map.get("dataSize"));
        jsonObject.setCode("200");
        jsonObject.setMsg("success");
        jsonObject.setData("level1SystemList", map.get("level1SystemList"));

        return jsonObject;
    }

    @RequestMapping("/show")
    public JsonObject show(@RequestParam(name = "level1SystemId") int level1SystemId) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.setData("System1", level1SystemService.findById(level1SystemId));

        WorkPlan workPlan = new WorkPlan(level1SystemId);
        jsonObject.setData("WorkPlan", workPlanService.selectByLevel1SystemIdAndTypeId(workPlan));

        Map<String, SecondarySystemFuncationMessage> system2FunMsgMap = new HashMap<>(SECONDARY_SYSTEM_NUM);
        system2FunMsgMap.put("s1", secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, FOUNDATION_PLATFORM_SYSTEM_NUM)));
        system2FunMsgMap.put("s2", secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, INTERFACE_SYSTEM_NUM)));
        system2FunMsgMap.put("s3", secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, SERVICE_SYSTEM_NUM)));
        system2FunMsgMap.put("s41",secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, APPLICATION_APPLET_SYSTEM_NUM)) );
        system2FunMsgMap.put("s42",secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, APPLICATION_H5_SYSTEM_NUM)));
        system2FunMsgMap.put("s43",secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, APPLICATION_CLIENT_SYSTEM_NUM)));
        system2FunMsgMap.put("s44",secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, APPLICATION_PC_SYSTEM_NUM)));
        system2FunMsgMap.put("s45",secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, APPLICATION_TENCENT_SYSTEM_NUM)));
        jsonObject.setData("System2fun", system2FunMsgMap);

        Map<String, List<SecondarySystemPeopleMessage>> system2PeopleMsgMap = new HashMap<>(SECONDARY_SYSTEM_NUM);
        system2PeopleMsgMap.put("s1", secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, FOUNDATION_PLATFORM_SYSTEM_NUM));
        system2PeopleMsgMap.put("s2", secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, INTERFACE_SYSTEM_NUM));
        system2PeopleMsgMap.put("s3", secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, SERVICE_SYSTEM_NUM));
        system2PeopleMsgMap.put("s41",secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, APPLICATION_APPLET_SYSTEM_NUM));
        system2PeopleMsgMap.put("s42",secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, APPLICATION_H5_SYSTEM_NUM));
        system2PeopleMsgMap.put("s43",secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, APPLICATION_CLIENT_SYSTEM_NUM));
        system2PeopleMsgMap.put("s44",secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, APPLICATION_PC_SYSTEM_NUM));
        system2PeopleMsgMap.put("s45",secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, APPLICATION_TENCENT_SYSTEM_NUM));
        jsonObject.setData("System2job", system2PeopleMsgMap);

        jsonObject.setCode("200");
        jsonObject.setMsg("success");

        return jsonObject;
    }

    @RequestMapping("/create")
    public JsonObject create(HttpServletRequest request, @RequestParam(name = "templateId") int templateId) {
        JsonObject jsonObject = new JsonObject();

        Integer userId = (Integer) request.getSession().getAttribute("userId");

        jsonObject.setData("modeItem", templateClient.findById(templateId));
        jsonObject.setData("level1SystemId", level1SystemService.create(templateId, userId));
        jsonObject.setCode("200");
        jsonObject.setMsg("success");

        return jsonObject;
    }

    @RequestMapping("/transmitMsg")
    public JsonObject transmitMsg(@RequestParam(name = "level1SystemId") int level1SystemId) throws IOException {
        JsonObject jsonObject = new JsonObject();

        List<String> numList = level1SystemService.transmitMsg(level1SystemId);

        ArrayList<String> usernameList = new ArrayList<>();

        for ( String num : numList ) {
            usernameList.add(userService.findById(num).getUsername());
        }

        jsonObject.setData("msg", usernameList);
        jsonObject.setCode("200");
        jsonObject.setMsg("success");

        return jsonObject;
    }

    @RequestMapping("/goEdit")
    public JsonObject goEdit(HttpServletRequest request, @RequestParam(name = "level1SystemId") int level1SystemId) {
        JsonObject jsonObject = new JsonObject();

        int modeId = Integer.valueOf(level1SystemService.findById(level1SystemId).getTemplateId());

        jsonObject.setMsg("success");
        jsonObject.setCode(level1SystemService.isOk(level1SystemId, String.valueOf(request.getSession().getAttribute("userId"))));
        jsonObject.setData("modeItem", templateClient.findById(modeId));

        return jsonObject;
    }

    @RequestMapping("/findSystem1")
    public JsonObject findSystem1(@RequestParam(name = "level1SystemId") int level1SystemId) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.setMsg("success");
        jsonObject.setCode("200");
        jsonObject.setData("level1System", level1SystemService.findById(level1SystemId));

        return jsonObject;
    }

    @RequestMapping("/saveSystem1")
    public JsonObject saveSystem1(@RequestBody Level1System level1System) {
        JsonObject jsonObject = new JsonObject();

        if(level1SystemService.update(level1System) == 1) {
            jsonObject.setMsg("success");
            jsonObject.setCode("200");
        } else {
            jsonObject.setMsg("error");
            jsonObject.setCode("500");
        }
        return jsonObject;
    }

    @RequestMapping("/findWorkPlan")
    public JsonObject findWorkPlan(@RequestParam(name = "level1SystemId") int level1SystemId,
                                   @RequestParam(name = "typeId") int typeId) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.setMsg("success");
        jsonObject.setCode("200");
        jsonObject.setData("workPlan", workPlanService.selectByLevel1SystemIdAndTypeId(new WorkPlan(level1SystemId,typeId)));

        return jsonObject;
    }

    @RequestMapping("/saveWorkPlan")
    public JsonObject saveWorkPlan(@RequestBody List<WorkPlan> workPlanList) {
        JsonObject jsonObject = new JsonObject();

        workPlanService.update(workPlanList);
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/findSystem2Data")
    public JsonObject findSystem2Data(@RequestParam(name = "level1SystemId") int level1SystemId,
                                      @RequestParam(name = "typeId") int typeId) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.setData("system2Data", secondarySystemPeopleMessageService.selectByLevel1SystemIdAndTypeId(level1SystemId, typeId));
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/saveSystem2Data")
    public JsonObject saveSystem2Data(@RequestBody List<SecondarySystemPeopleMessage> secondarySystemPeopleMessageList) {
        JsonObject jsonObject = new JsonObject();

        secondarySystemPeopleMessageService.update(secondarySystemPeopleMessageList);
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/findSystem2Function")
    public JsonObject findSystem2Function(@RequestParam(name = "level1SystemId") int level1SystemId,
                                          @RequestParam(name = "typeId") int typeId) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.setData("system2Function", secondarySystemFunctionMessageService.selectByLevel1SystemIdAndTypeId(new SecondarySystemFuncationMessage(level1SystemId, typeId)));
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/saveSystem2Function")
    public JsonObject saveSystem2Function(@RequestBody SecondarySystemFuncationMessage secondarySystemFuncationMessage) {
        JsonObject jsonObject = new JsonObject();

        secondarySystemFunctionMessageService.update(secondarySystemFuncationMessage);
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/findUrl")
    public JsonObject findUrl(HttpServletRequest request, @RequestParam(name = "level1SystemId") int level1SystemId) {
        JsonObject jsonObject = new JsonObject();

        int port = request.getServerPort();
        String prefix = "localhost:"+port+"/index.html";
        String suffix = level1SystemService.findById(level1SystemId).getSendUrl();
        jsonObject.setData("sendUrl", prefix + suffix);
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        return jsonObject;
    }

    @RequestMapping("/confirm")
    public JsonObject confirm(@RequestParam(name = "level1SystemId") int level1SystemId) {
        JsonObject jsonObject = new JsonObject();

        Level1System level1System = level1SystemService.findById(level1SystemId);
        String state = level1System.getState().substring(0, level1System.getState().length()-1);
        level1System.setState(state+"3");

        if(level1SystemService.update(level1System) == 1) {
            jsonObject.setMsg("success");
            jsonObject.setCode("200");
        }
        return jsonObject;
    }

    @RequestMapping("/setSendState")
    public JsonObject setSendState(@RequestParam(name = "tableId") int tableId,
                                   @RequestParam(name = "haoyouId") int haoyouId) {
        JsonObject jsonObject = new JsonObject();

        Level1System level1System = level1SystemService.findById(tableId);
        String state = level1System.getState().substring(0, level1System.getState().length()-1)+"2";
        state += "-"+haoyouId+"_1";

        //localhost:8080/index.html?tableId=18&preId=211&localtime=2020-03-28 15:46:44
        String suffix = "?tableId="+tableId+"&preId="+haoyouId+"&localtime="+ DataUtil.getCurrentTime();

        level1System.setState(state);
        level1System.setSendUrl(suffix);

        if(level1SystemService.update(level1System) == 1) {
            jsonObject.setMsg("success");
            jsonObject.setCode("200");
        }
        return jsonObject;
    }

    @RequestMapping("/send")
    public JsonObject send(HttpServletRequest request,
                           @RequestParam(name = "url") String url,
                           @RequestParam(name = "tableId") int tableId,
                           @RequestParam(name = "preId") int preId) {
        JsonObject jsonObject = new JsonObject();

        //链接无效
        Level1System system = new Level1System();
        system.setSendUrl(url);
        if(level1SystemService.findByUrl(system) == null) {
            jsonObject.setMsg("error");
            jsonObject.setCode("500");
        }

        //加好友
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Address address = new Address();
        address.setUserId(userId);
        address.setHaoyouId(preId);
        if(addressService.findByUserIdAndHaoyouId(address) == null) {
            addressService.save(address);
        }

        //修改转发状态
        Level1System level1System = level1SystemService.findById(tableId);
        String state = level1System.getState().substring(0, level1System.getState().length()-1)+"2";
        state += "-"+userId+"_1";

        //修改转发链接
        String suffix = "?tableId="+tableId+"&preId="+userId+"&localtime="+ DataUtil.getCurrentTime();

        level1System.setState(state);
        level1System.setSendUrl(suffix);

        if(level1SystemService.update(level1System) == 1) {
            jsonObject.setMsg("success");
            jsonObject.setCode("200");
        }
        return jsonObject;
    }

    @RequestMapping("/remind")
    public JsonObject remind(@RequestParam(name = "level1SystemId") int level1SystemId){

        JsonObject jsonObject = new JsonObject();

        if(contractRemindService.updateByRemind(level1SystemId) == 1) {
            jsonObject.setMsg("success");
            jsonObject.setCode("200");
        }

        return jsonObject;
    }

    @RequestMapping("/detail")
    public JsonObject detail(HttpServletRequest request){

        JsonObject jsonObject = new JsonObject();

        int userId = (int)request.getSession().getAttribute("userId");

        jsonObject.setData("remindInfo", contractRemindService.findRemindByRemindId(userId));
        jsonObject.setMsg("success");
        jsonObject.setCode("200");

        contractRemindService.updateByRead(userId);

        return jsonObject;
    }

    @RequestMapping("/deleteById")
    public JsonObject deleteById(@RequestParam(name = "level1SystemId") int level1SystemId){

        JsonObject jsonObject = new JsonObject();

        contractRemindService.deleteByTableId(level1SystemId);
        secondarySystemFunctionMessageService.deleteByTableId(level1SystemId);
        secondarySystemPeopleMessageService.deleteByTableId(level1SystemId);
        workPlanService.deleteByTableId(level1SystemId);
        level1SystemService.deleteById(level1SystemId);

        jsonObject.setMsg("success");
        jsonObject.setCode("200");


        return jsonObject;
    }
}
